var express = require('express');
var db = require('../db.js')
var router = express.Router()
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
let md5 = require('md5-nodejs')

router.get('/',function(req,res){
    res.send('user')
})

//用户登录
router.post('/login', urlencodedParser, async function (req, res) {
    let { loginName, loginKey, phoneNum} = req.body
    let sql = `select id from user where loginName='${loginName}' and loginKey='${loginKey}'`;
    if(phoneNum){
        sql = `select id from user where phoneNum='${phoneNum}' and loginKey='${loginKey}'`;
    }
    let r = await db.doSql(sql)
    // console.log(r)
    if (r[0]) {
        let ken = await getToken(r[0].id)
        r[0].token = ken
        res.send(db.getData({ token: ken }))
    } else {
        res.send(db.handleNoResults())
    }
})

async function getToken(id) {
    let token = ''
    let sql = `select token from token where uid=${id}`
    let r = await db.doSql(sql)
    // console.log(r)
    if (r.length > 0 && r[0].token) {
        token = r[0].token
    } else {
        token = md5('zxwx' + id + Date.now())
        let sqla = `insert into token (token,uid) values('${token}','${id}')`
        let r1 = db.doSql(sqla)
        // console.log(r1)
    }
    return token
}

//用户信息
router.get('/getInfo', async (req, res) => {
    let { token } = req.query
    // console.log(token)
    let sql = `select u.id,u.name,u.avatar,u.roles,u.phoneNum,u.email from token as t,user as u where t.token='${token}' and t.uid=u.id`
    let r = await db.doSql(sql)
    // console.log(sql)
    res.send(db.getData(r))
})

//退出
router.post('/logout', urlencodedParser, async (req, res) => {
    let { token } = req.body
    // console.log(token)
    let sql = `delete from token where token=?`
    let r = await db.doSql(sql, [token])
    if (r.affectedRows) {
        res.send(db.getData({}))
    } else {
        res.send(db.handleNoResults())
    }
})

//注册用户信息
router.post('/register', urlencodedParser, async function (req, res) {
    let { name, loginName, loginKey, avatar,phoneNum,email } = req.body
    console.log(phoneNum)
    let sql = `insert into user (name,loginName,loginKey,avatar,phoneNum,email) values ('${name}','${loginName}','${loginKey}','${avatar}','${phoneNum}','${email}')`
    let r = await db.doSql(sql)
    console.log(sql)
    res.send(db.addData(r))
})

module.exports = router